#include "PlayerController.h"

PlayerController::PlayerController()
{
}
PlayerController::~PlayerController()
{
}
void PlayerController::InitPlayer(World *w)
{
	pitch =0;
	heading = 0;
	this->p_world = w;
	this->plc_node = p_world->window->get_render().attach_new_node("plc");
	this->plc_cam_node = p_world->window->get_render().attach_new_node("plc_cam");
	this->plc_cam_node.reparent_to(this->plc_node);
	this->player_model = p_world->window->load_model(plc_node, "data/models/panda");
	player_model.set_scale(0.2,0.2,0.2);
	p_world->window->load_model(player_model, "data/models/panda-walk");
	auto_bind(player_model.node(), player_anim);
	player_anim.get_anim(0)->get_part()->set_blend_type(PartBundle::BT_linear);
	w->window->get_camera_group().reparent_to(plc_cam_node);
	plc_cam_node.get_child(0).set_pos(0,-10,10);
	this->pl_controller = new KCC(p_world->p_world,&plc_node,p_world->window,1.8,1.0,0.1,0.5,-9.81);
	this->pl_controller->setMaxSlope(10,false);
	this->pl_controller->set_pos(LVector3f(0,0,10));
	//this->pl_controller->startFly();
}
bool PlayerController::Update()
{
	LVector3f forward_v = plc_cam_node.get_mat().get_row3(1);
	double force = 0;
	heading -= p_world->mx;
	pitch -= p_world->my;
	plc_cam_node.get_child(0).look_at(plc_node.get_pos());
	plc_cam_node.set_h(heading);
	plc_cam_node.set_p(pitch);
	player_model.set_h(heading+180);
	//events
	if(p_world->down_keys.find("w") != p_world->down_keys.end()){
		force = 10;
		if(!player_anim.is_playing("panda_soft")){
			player_anim.get_anim(0)->set_play_rate(1.0);
			player_anim.loop("panda_soft",true);
		}
	}else if(p_world->down_keys.find("s") != p_world->down_keys.end()){
		force = -8;
		if(!player_anim.is_playing("panda_soft")){
			player_anim.get_anim(0)->set_play_rate(-1.0);
			player_anim.loop("panda_soft",true);
		}
	}else{
	player_anim.get_anim(0)->set_play_rate(1.0);
	player_anim.stop("panda_soft");
	}
	if(p_world->down_keys.find("space") != p_world->down_keys.end()){
		pl_controller->startJump(5.0f);
	}
	if(p_world->once_down_keys.find("wheel_up") != p_world->once_down_keys.end()){
		if(plc_cam_node.get_child(0).get_y() < -2)
			this->plc_cam_node.get_child(0).set_y(plc_cam_node.get_child(0).get_y()+1);
		p_world->Remove("wheel_up",&p_world->once_down_keys);
	}
	if(p_world->once_down_keys.find("wheel_down") != p_world->once_down_keys.end()){
		if(plc_cam_node.get_child(0).get_y() > -20)
			this->plc_cam_node.get_child(0).set_y(plc_cam_node.get_child(0).get_y()-1);
		p_world->Remove("wheel_down",&p_world->once_down_keys);
	}
	pl_controller->setLinearMovement(forward_v*force);
	pl_controller->update();
	return true;
}